//
//  STRenewViewModel.m
//  EnvironmentalProtection
//
//  Created by HCreater on 2018/12/19.
//  Copyright © 2018年 HCreater. All rights reserved.
//

#import "STRenewViewModel.h"

#import "RenewChooseCityCellModel.h"

#import "ReckonData.h"

@interface STRenewViewModel()

@property (nonatomic, readwrite, assign) BOOL isAllChoose;
@property (nonatomic, readwrite, assign) BOOL isCanPay;

@property (nonatomic, readwrite, strong) NSDictionary* keepPayInfo;
@property (nonatomic, readwrite, strong) NSDictionary* keepOrderInfo;

@property (nonatomic, readwrite, strong) RACCommand* calPriceCmd;
@property (nonatomic, readwrite, strong) RACCommand* allChooseCmd;
@property (nonatomic, readwrite, strong) RACCommand* refreshCityCmd;
@property (nonatomic, readwrite, strong) RACCommand* selectCityChooseCmd;
@property (nonatomic, readwrite, strong) RACCommand* cityChooseCmd;
@property (nonatomic, readwrite, strong) RACCommand* dateChooseCmd;
@property (nonatomic, readwrite, strong) RACCommand* requestDataCmd;
@property (nonatomic, readwrite, strong) RACCommand* selectCmd;
@property (nonatomic, readwrite, strong) RACCommand* payCmd;


@end

@implementation STRenewViewModel

- (void)initialize
{
    [super initialize];
    
    @weakify(self);
    
    self.chooseDateIndex = -1;
    self.chooseCityNum = 0;
    self.selectChooseNum = 0;
    self.priceNum = 0;
    self.originPriceNum = 0;
    self.price = @"0.00";
    self.originPrice = @"原价¥0.00";
    self.strChooseCityNum = @"已选0个城市";
    self.strSelectChooseNum = @"已选0";
    self.charge = @"可用0生态币抵用0元";
    self.isChargeSwitch = NO;
    self.isCanPay = NO;
    
    self.cellHeight = 46.0f;
    
    self.lastPage = 100;
    self.shouldMultiSections = NO;
    /// viewDidLoad后加载数据
    self.shouldRequestRemoteDataOnViewDidLoad = NO;
    /// 允许下拉刷新
    self.shouldPullDownToRefresh = NO;
    /// 允许上拉加载
    self.shouldPullUpToLoadMore = NO;
    
    RAC(self, price) = [RACObserve(self, priceNum) map:^id(id value)
    {
        return [NSString decimalwithFormat:@"0.00" floatV:[value floatValue]];
    }];
    
    RAC(self, originPrice) = [RACObserve(self, originPriceNum) map:^id(id value)
    {
        return [NSString decimalwithFormat:@"0.00" floatV:[value floatValue]];
    }];
    
    RACSignal* changeDateIndexSignal = RACObserve(self, chooseDateIndex);
    RACSignal* changeChooseCityNumSignal = RACObserve(self, chooseCityNum);
    RACSignal* changeSelectChooseNumSignal = RACObserve(self, selectChooseNum);
    RACSignal* changeChargeSwitchSignal = RACObserve(self, isChargeSwitch);
    
    RAC(self, strChooseCityNum) = [[changeChooseCityNumSignal replay] map:^id(id value)
    {
        NSInteger _chooseCityNum = [value integerValue];
        
        return HCStrFormat(@"已选%d个城市", (int)_chooseCityNum);
    }];
    
    RAC(self, strSelectChooseNum) = [[[changeSelectChooseNumSignal replay] doNext:^(id x)
    {
        @strongify(self);
        self.isAllChoose = self.selectChooseNum == self.chooseCityNum;
    }] map:^id(id value)
    {
       NSInteger _chooseCount = [value integerValue];
       
       return HCStrFormat(@"已选%d", (int)_chooseCount);
    }];
    
    RACSignal* request_cDateIndexSignal = [[changeDateIndexSignal replay] filter:^BOOL(id value) {
        NSInteger dateIndex = [value integerValue];
        
        return dateIndex != -1;
    }];
    RACSignal* request_cSelectChooseNumSignal = [changeSelectChooseNumSignal replay];
    RACSignal* request_cChargeSwitchSignal = [changeChargeSwitchSignal replay];
    
    RACSignal* requestSignal = [[RACSignal combineLatest:@[request_cDateIndexSignal, request_cSelectChooseNumSignal, request_cChargeSwitchSignal]] flattenMap:^RACStream *(id value)
    {
        @strongify(self);
        
        self.isCanPay = NO;
        
        RACTuple* tuple = value;
        
        NSInteger dateIndex = [tuple.first integerValue];
        NSInteger selectChooseNum = [tuple.second integerValue];
        BOOL isSwitch = [tuple.third boolValue];
        
        NSLog(@"DateIndex : %d | SelectChooseNum : %d | IsSwitch : %@", (int)dateIndex, (int)selectChooseNum, isSwitch?@"YES":@"NO");
        
        if (selectChooseNum <= 0)
        {
            self.priceNum = 0;
            self.originPriceNum = 0;
            
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [subscriber sendNext:nil];
                [subscriber sendCompleted];
                
                return nil;
            }];
        }
        else
        {
            NSString* strTime = HCStrFormat(@"%d", (int)(dateIndex + 1));
            
            NSMutableArray* strAreas = [NSMutableArray array];
            for (RenewChooseCityCellModel* cm in self.dataSource)
            {
                ProvinceListData* curData = cm.data;
                
                if (cm.isChoose)
                {
                    [strAreas addObject:curData.areaID];
                }
            }
            NSString* strArea = [strAreas componentsJoinedByString:@","];
            
            return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                [subscriber sendNext:@{@"Area":strArea, @"Time":strTime}];
                [subscriber sendCompleted];
                
                return nil;
            }];
        }
    }];
    [requestSignal subscribeNext:^(id x)
    {
        @strongify(self);
        
        if (x != nil)
        {
            self.keepPayInfo = [NSDictionary dictionaryWithDictionary:x];
            
            [self.calPriceCmd execute:x];
        }
    }];
    
    self.calPriceCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        NSString* strArea = input[@"Area"];
        NSString* strTime = input[@"Time"];
        
        return [self _requestCalPriceSignal:strArea time:strTime];
    }];
    
    self.allChooseCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
     
        [self _allChoose];
     
        return [RACSignal empty];
    }];
    
    self.refreshCityCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        [self refreshCityDatas:input];
        
        return [RACSignal empty];
    }];
    
    self.selectCityChooseCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
    {
        @strongify(self);
        
        @weakify(self);
        return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
        {
            @strongify(self);
            
            [self _selectCityChooseByIndexPath:input];
            
            [subscriber sendNext:nil];
            [subscriber sendCompleted];
            
            return nil;
        }];
    }];
    
    self.cityChooseCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                                {
                                    @strongify(self);
                                    
                                    @weakify(self);
                                    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                                            {
                                                @strongify(self);
                                                
                                                [subscriber sendNext:nil];
                                                [subscriber sendCompleted];
                                                
                                                return nil;
                                            }];
                                }];
    
    self.dateChooseCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                          {
                              @strongify(self);
                              
                              @weakify(self);
                              return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
                                      {
                                          @strongify(self);
                                          
                                          [subscriber sendNext:nil];
                                          [subscriber sendCompleted];
                                          
                                          return nil;
                                      }];
                          }];
    
    self.payCmd = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input)
                   {
                       @strongify(self);
                       
                       @weakify(self);
                       if (self.isCanPay)
                       {
                           return [self _requestOrderSignal];
                           
//                           return [[[self _requestPaySignal] flattenMap:^RACStream *(id value)
//                           {
//                               @strongify(self);
//
//                               self.keepOrderInfo = value;
//
//                               NSString* money = [NSString decimalwithFormat:@"0.00" floatV:[self.keepOrderInfo[@"pay_price"] floatValue]];
//
//                               return [self _requestCalWXPaySignal:self.keepOrderInfo[@"spread_sn"] money:money];
//                           }] flattenMap:^RACStream *(id value)
//                           {
//                               @strongify(self);
//
//                               return [self _requestPayNotifySignal:self.keepOrderInfo[@"spread_id"]];
//                           }];
                       }
                       
                       return [RACSignal error:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:@"尚未可支付"}]];
                   }];
}

- (NSArray*)cityAreaIDs
{
    NSMutableArray* cityAreaIDs = [NSMutableArray array];
    
    for (RenewChooseCityCellModel* cm in self.dataSource)
    {
        ProvinceListData* pListData = cm.data;
        
        [cityAreaIDs addObject:pListData.areaID];
    }
    
    return cityAreaIDs;
}

- (void)checkInit
{
    DataManager* dm = [DataManager sharedDataManager];
    
    if (self.buildAreaIDs && self.buildAreaIDs.count>0)
    {
        NSMutableArray* cityInfos = [NSMutableArray array];
        for (NSInteger index=0; index<self.buildAreaIDs.count; index++)
        {
            NSString* curAreaID = self.buildAreaIDs[index];
            
            [cityInfos addObject:[dm findCityDataBy:curAreaID]];
        }
        
        [self.refreshCityCmd execute:cityInfos];
    }
}

- (void)_allChoose
{
    BOOL isAllChoose = !self.isAllChoose;
    
    NSInteger count = self.dataSource.count;
    for (NSInteger index=0; index<count; index++)
    {
        RenewChooseCityCellModel* cellModel = self.dataSource[index];
        cellModel.isChoose = isAllChoose;
    }
    
    [self _updateChoosedCityNum];
}

- (void)_selectCityChooseByIndexPath:(NSIndexPath*)indexPath
{
    NSInteger count = self.dataSource.count;
    for (NSInteger index=0; index<count; index++)
    {
        RenewChooseCityCellModel* cellModel = self.dataSource[index];
        
        if (indexPath.row == index)
        {
            cellModel.isChoose = !cellModel.isChoose;
            
            break;
        }
    }
    
    [self _updateChoosedCityNum];
}

- (void)_updateChoosedCityNum
{
    NSInteger chooseCount = 0;
    NSInteger count = self.dataSource.count;
    for (NSInteger index=0; index<count; index++)
    {
        RenewChooseCityCellModel* cellModel = self.dataSource[index];
        
        if (cellModel.isChoose)
        {
            chooseCount++;
        }
    }
    
    self.selectChooseNum = chooseCount;
}

- (void)refreshCityDatas:(NSArray*)cityDatas
{
    @weakify(self);
    NSArray *viewModels = [cityDatas.rac_sequence map:^id(ProvinceListData* data)
                           {
                               @strongify(self);
                               
                               @weakify(self);
                               RenewChooseCityCellModel *cellModel = [[RenewChooseCityCellModel alloc] initWithData:data cellHeight:self.cellHeight];
                               [[cellModel.closeCommand.executionSignals.switchToLatest deliverOnMainThread] subscribeNext:^(id x)
                               {
                                   @strongify(self);
                                   
                                   NSString* areaID = x;
                                   
                                   [self _removeCityByAreaID:areaID];
                               }];
                               
                               return cellModel;
                           }].array;

    self.dataSource = viewModels;
    
    self.chooseCityNum = self.dataSource.count;
    
    [self _updateChoosedCityNum];
}

- (void)_removeCityByAreaID:(NSString*)areaID
{
    NSInteger count = self.dataSource.count;
    NSInteger delIndex = -1;
    for (NSInteger index=0; index<count; index++)
    {
        RenewChooseCityCellModel *cellModel = self.dataSource[index];
        ProvinceListData* pListData = cellModel.data;
        if ([pListData.areaID isEqualToString:areaID])
        {
            delIndex = index;
            
            break;
        }
    }
    
    NSMutableArray* newDataSources = [NSMutableArray arrayWithArray:self.dataSource];
    [newDataSources removeObjectAtIndex:delIndex];
    
    self.dataSource = newDataSources;
    
    self.chooseCityNum = self.dataSource.count;
    
    [self _updateChoosedCityNum];
}

- (RACSignal*)_requestCalPriceSignal:(NSString*)area time:(NSString*)time
{
    @weakify(self);
    
    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
    
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);
                
                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_spread_reckon params:interface_param_spread_reckon(um.userData.userID, area, time)] subscribeNext:^(id x)
                 {
                     @strongify(self);
                     
                     ReckonData* reckonData = [ReckonData modelWithJSON:x];
                     
                     NSInteger userMoney = [reckonData.userMoney integerValue];
                     
                     self.isCanPay = YES;
                     self.charge = HCStrFormat(@"可用%d生态币抵用%d元", (int)userMoney, (int)userMoney);
                     self.priceNum = [reckonData.price integerValue];
                     self.originPriceNum = [reckonData.primeCost integerValue];
                     
                     [subscriber sendNext:reckonData];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     [subscriber sendCompleted];
                 }];
                
                return nil;
            }];
}

- (RACSignal*)_requestOrderSignal
{
    @weakify(self);

    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];

    NSString* strArea = self.keepPayInfo[@"Area"];
    NSString* strTime = self.keepPayInfo[@"Time"];
    NSString* strIsCharge = self.isChargeSwitch ? @"1" : @"0";

    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
            {
                @strongify(self);

                @weakify(self);
                [[AFNetWorkUtils racPOSTWthURL:url_interface_spread_submit params:interface_param_spread_submit(um.userData.userID, strArea, strTime, strIsCharge)] subscribeNext:^(id x)
                 {
                     @strongify(self);

                     //                     "spread_id": "4",
                     //                     "pay_price": 2592,
                     //                     "spread_sn": "907450191220181219153143"

                     [subscriber sendNext:x];
                     [subscriber sendCompleted];
                 } error:^(NSError *error)
                 {
                     [subscriber sendCompleted];
                 }];

                return nil;
            }];
}
//
//- (RACSignal*)_requestPayNotifySignal:(NSString*)orderID
//{
//    @weakify(self);
//
//    UserManagerV2* um = [UserManagerV2 sharedUserManagerV2];
//
//    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber)
//            {
//                @strongify(self);
//
//                [[AFNetWorkUtils racPOSTWthURL:url_interface_order_paynotify params:interface_param_order_paynotify(orderID)] subscribeNext:^(id x)
//                 {
//                     [subscriber sendNext:@"PayFinish"];
//                     [subscriber sendCompleted];
//                 } error:^(NSError *error)
//                 {
//                     NSString* strError = [error.userInfo[customErrorInfoKey] isNotBlank] ? error.userInfo[customErrorInfoKey] : @"支付回调失败";
//                     [subscriber sendError:[NSError errorWithDomain:SUCommandErrorDomain code:SUCommandErrorCode userInfo:@{SUCommandErrorUserInfoKey:strError}]];
//                     [subscriber sendCompleted];
//                 }];
//
//                return nil;
//            }];
//}
//
//- (RACSignal*)_requestCalWXPaySignal:(NSString*)tradeNo money:(NSString*)money
//{
//    @weakify(self)
//    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
//        @strongify(self);
//
//        NSString* price = money;
//
//        NSDecimalNumber *priceDN = [NSDecimalNumber decimalNumberWithString:price];
//        priceDN = [priceDN decimalNumberByMultiplyingBy:[NSDecimalNumber decimalNumberWithString:@"100"]];
//
//        WTPayOrderItem* payOrderItem = [[WTPayOrderItem alloc] init];
//        payOrderItem.orderBody = @"";
//        payOrderItem.orderName = @"生态推广订单";
//        payOrderItem.orderPrice = [NSString stringWithFormat:@"%d", [priceDN intValue]];
//        payOrderItem.orderOutTradeNO = tradeNo;
//
//        [WTPayManager wtPayOrderItem:payOrderItem payType:WTPayTypeWeixin result:^(NSDictionary *payResult, NSString *error) {
//
//            if (error)
//            {
//                NSString * errorInfo = error;
//                NSMutableDictionary *userInfo = [NSMutableDictionary dictionary];
//                userInfo[customErrorInfoKey] = errorInfo;
//                NSError * error = [NSErrorHelper createErrorWithUserInfo:userInfo domain:@"WTPayManager"];
//                [subscriber sendError:error];
//                [subscriber sendCompleted];
//            }
//            else
//            {
//                [subscriber sendNext:@YES];
//                [subscriber sendCompleted];
//            }
//        }];
//
//        return nil;
//    }];
//}

@end
